//
//  NSChatListCell.m
//  Meboo
//
//  Created by kyo on 2023/10/16.
//

#import "NSChatListCell.h"
#import "NSModelDetailViewController.h"
@interface NSChatListCell ()
//vip头像框
@property(nonatomic,strong) UIImageView *vipImageView;
//最近一条消息message
@property (nonatomic, strong) UILabel *messageLab;
//name
@property (nonatomic, strong) UILabel *nameLab;
//最近一条消息的时间
@property (nonatomic, strong) UILabel *timeLab;
//未读数
@property (nonatomic, strong) UILabel *numLab;
//头像
@property (nonatomic, strong) UIImageView *avatarImageView;
//在线状态
@property (nonatomic, strong) UIImageView *stateView;
//targetId
@property (nonatomic, copy) NSString *targetId;
@end

@implementation NSChatListCell


#pragma mark - Life Cycle
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self setupUI];
    }
    return self;
}

#pragma mark - Public Method
//数据的处理和赋值
- (void)setModel:(RCConversationModel *)model {
    self.targetId = model.targetId;
    //比较最后一条收和发的时间,哪个大,那个是最新消息
    long long time = model.receivedTime > model.sentTime ? model.receivedTime : model.sentTime;
    //消息的发送者信息
    RCUserInfo *userInfo = [[RCIM sharedRCIM] getUserInfoCache:model.targetId];
    if (userInfo.portraitUri.length > 0) {
        [self.avatarImageView sd_setImageWithURL:[NSURL URLWithString:userInfo.portraitUri]];
    } else {
        [self.avatarImageView sd_setImageWithURL:[NSURL URLWithString:@"https://storage.googleapis.com/meboo-online-b68e7.appspot.com/mebooRegisterDefult/RegisterPhotoMebooDefult.jpg"]];
    }
    
    self.timeLab.text = [self cStringFromTimestamp:time];
    //消息未读数处理
    self.numLab.text = [NSString stringWithFormat:@"%ld",model.unreadMessageCount];
    if (model.unreadMessageCount > 99) {
        self.numLab.hidden = NO;
        self.numLab.text = @"99+";
    } else if (model.unreadMessageCount == 0) {
        self.numLab.hidden = YES;
    } else {
        self.numLab.hidden = NO;
    }
    
    //name处理,剔除特殊符号以Meboo代替
    self.nameLab.text = userInfo.name;
    if ([self.nameLab.text isEqualToString:@"user<>"]) {
        self.nameLab.text = @"Meboo";
    }
    
    //最后一条message
    self.messageLab.text = model.lastestMessage.conversationDigest;
    
    //model.extend是id类型 作为字典使用必须先判断类型
    if ([model.extend isKindOfClass:[NSDictionary class]]) {
        //在线状态标识符的判断
        if ([[model.extend valueForKey:@"online"] isEqualToString:@"1"]) {
            self.stateView.hidden = NO;
        } else {
            self.stateView.hidden = YES;
        }
        //fc状态标识符的判断
        if ([[model.extend valueForKey:@"flashchat"] isEqualToString:@"1"]) {
            [self getNameAttributWithString:self.nameLab.text];
        }
    }
    
    //userType 2:CM 显示VIP标识 3:M 不显示VIP标识
//    if ([model.userType integerValue] == 2) {
//        self.vipImageView.hidden = NO;
//        self.iconImageView.layer.borderColor = HEXS(@"A84FFF").CGColor;
//    } else {
//        self.vipImageView.hidden = YES;
//        self.iconImageView.layer.borderColor = UIColor.whiteColor.CGColor;
//    }
}

// 时间戳—>字符串时间
- (NSString *)cStringFromTimestamp:(long long)timestamp {
    timestamp = timestamp/1000;
    //时间戳转时间的方法
    NSDate *timeData = [NSDate dateWithTimeIntervalSince1970:timestamp];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"HH:mm"];
    NSString *strTime = [dateFormatter stringFromDate:timeData];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    if ([calendar isDateInToday:timeData]) {
        //是否是今天
        return strTime;
    } else if ([calendar isDateInYesterday:timeData]) {
        //是否是昨天
        return @"Yesterday";
    } else {
        //其他直接显示月/天日期
        [dateFormatter setDateFormat:@"MM/dd"];
        return [dateFormatter stringFromDate:timeData];
    }
}

#pragma mark - Private Method
//处理侧滑删除的cell--的侧滑状态补偿
- (void)setFrame:(CGRect)frame {
    frame.origin.y += MBHeightScale(10);
    frame.size.height -= MBHeightScale(10);
    [super setFrame:frame];
}

//nameFC 图文混排
- (void)getNameAttributWithString:(NSString *)nameStr {
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ ",nameStr]];
    NSTextAttachment *attach = [NSTextAttachment new];
    attach.image = ImageWithName(@"chat_list_fc");
    NSAttributedString *attachString = [NSAttributedString attributedStringWithAttachment:attach];
    [string appendAttributedString:attachString];
    self.nameLab.attributedText = string;
}

#pragma mark - Action
//点击头像跳转modelDetail页面
- (void)clickAvatar {
    NSModelDetailViewController *modelDetailVc = [NSModelDetailViewController new];
    modelDetailVc.modelStyle = ChatModelDetail;
    modelDetailVc.userId = self.targetId;
    [self.currentViewController.navigationController pushViewController:modelDetailVc animated:YES];
}

#pragma mark - UI
- (void)setupUI {
    self.backgroundColor = UIColor.clearColor;
    
    [self.contentView addSubview:self.avatarImageView];
    [self.avatarImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.contentView);
        make.left.mas_equalTo(MBWidthScale(20));
        make.width.height.mas_equalTo(MBHeightScale(48));
    }];
    
    [self.contentView addSubview:self.vipImageView];
    [self.vipImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(MBWidthScale(18));
        make.top.mas_equalTo(MBHeightScale(3));
        make.width.height.mas_equalTo(MBHeightScale(19));
    }];
    
    [self.contentView addSubview:self.nameLab];
    [self.nameLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.contentView.mas_centerY).offset(MBHeightScale(-2));
        make.left.equalTo(self.avatarImageView.mas_right).offset(MBWidthScale(12));
        make.right.mas_equalTo(MBWidthScale(-52));
    }];
    
    [self.contentView addSubview:self.messageLab];
    [self.messageLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentView.mas_centerY).offset(MBHeightScale(2));
        make.right.mas_equalTo(MBWidthScale(-52));
        make.left.equalTo(self.avatarImageView.mas_right).offset(MBWidthScale(15));
    }];
    
    
    [self.contentView addSubview:self.timeLab];
    [self.timeLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.nameLab);
        make.right.mas_equalTo(MBWidthScale(-20));
    }];
    
    [self.contentView addSubview:self.numLab];
    [self.numLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.messageLab);
        make.right.mas_equalTo(-MBWidthScale(20));
        make.width.height.mas_equalTo(MBHeightScale(16));
    }];
    
    [self.contentView addSubview:self.stateView];
    [self.stateView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.equalTo(self.avatarImageView);
        make.width.height.mas_equalTo(MBHeightScale(14));
    }];
}

#pragma mark - Setter && Getter

- (UILabel *)nameLab {
    if (!_nameLab) {
        _nameLab = [[UILabel alloc] init];
        _nameLab.font = MBHelBoldFontSizeScale(16);
        _nameLab.textColor = HEXS(@"333333");
    }
    return _nameLab;
}

- (UILabel *)messageLab {
    if (!_messageLab) {
        _messageLab = [[UILabel alloc] init];
        _messageLab.font = MBHelFontSizeScale(12);
        _messageLab.textColor = [UIColor colorWithRed:51 / 255.0 green:51 / 255.0 blue:51 / 255.0 alpha:0.48];
    }
    return _messageLab;
}

- (UILabel *)timeLab {
    if (!_timeLab) {
        _timeLab = [[UILabel alloc] init];
        _timeLab.font = MBHelFontSizeScale(12);
        _timeLab.textColor = [UIColor colorWithRed:51 / 255.0 green:51 / 255.0 blue:51 / 255.0 alpha:0.48];
    }
    return _timeLab;
}

//- (UIButton *)numBtn {
//    if (!_numBtn) {
//        _numBtn = [[UIButton alloc] init];
//        _numBtn.layer.cornerRadius = MBHeightScale(8);
//        _numBtn.backgroundColor = HEXS(@"FF218B");
//        _numBtn.titleLabel.font = MBHelBoldFontSizeScale(12);
//        [_numBtn setTitleColor:HEXS(@"ffffff") forState:0];
//        _numBtn.hidden = YES;
//    }
//    return _numBtn;
//}

- (UILabel *)numLab {
    if (!_numLab) {
        _numLab = [UILabel new];
        _numLab.text = @"0";
        _numLab.textAlignment = NSTextAlignmentCenter;
        _numLab.backgroundColor = HEXS(@"FF218B");
        _numLab.layer.cornerRadius = MBHeightScale(8);
        _numLab.layer.masksToBounds = YES;
        _numLab.font = MBHelBoldFontSizeScale(12);
        _numLab.font = MBHelBoldFontSizeScale(8);
        _numLab.textColor = HEXS(@"ffffff");
    }
    return _numLab;
}

- (UIImageView *)avatarImageView {
    if (!_avatarImageView) {
        _avatarImageView = [UIImageView new];
        _avatarImageView.userInteractionEnabled = YES;
        _avatarImageView.contentMode = UIViewContentModeScaleAspectFill;
        _avatarImageView.layer.cornerRadius = MBHeightScale(24);
        _avatarImageView.layer.masksToBounds = YES;
        _avatarImageView.image = [UIImage imageNamed:@"home_icon_self"];
        
        _avatarImageView.layer.borderColor = HEXS(@"A84FFF").CGColor;
        _avatarImageView.layer.borderWidth = 1;
        
        UITapGestureRecognizer *avatarTap =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickAvatar)];
        [_avatarImageView addGestureRecognizer:avatarTap];
    }
    return _avatarImageView;
}

- (UIImageView *)stateView {
    if (!_stateView) {
        _stateView = [UIImageView new];
        _stateView.image = ImageWithName(@"chat_state");
        _stateView.hidden = YES;
    }
    return _stateView;
}

- (UIImageView *)vipImageView {
    if (!_vipImageView) {
        _vipImageView = [UIImageView new];
        _vipImageView.image = ImageWithName(@"home_list_vip_icon");
    }
    return _vipImageView;
}
@end
